<template>
  <el-select v-model="innerValue"
             :disabled="$attrs['disabled']"
             :placeholder="$attrs['placeholder']"
             clearable=""
             @change="(val)=>changeValue(val)"
             :size="$attrs['size']"
             :multiple="true"
  >
    <el-option :key="item.label" :value="item.label" :label="item.label" v-for="item in $data.options" />
  </el-select>
</template>
<script>
  import { ajaxDicList } from '@/utils/dic';

  export default {
    data() {
      return {
        innerValue: [],
        options: [],
      };
    },
    props: {
      code: { type: [String, Number], require: true },
      value: { type: [String, Number, Array] },
      //check 模式
      checkMode: { type: Boolean, default: false },
      //按钮模式
      buttonMode: { type: Boolean, default: true },
    },
    mounted() {
      this.ajaxList().then(res => {
        if (this.$props.value != undefined && this.$props.value != null) {
          this.innerValue = this.$props.value;
        }
      });
    },
    watch: {
      value(_val) {
        if (_val != undefined && _val != null) {
          this.innerValue = _val;
        }
      },
    },
    methods: {
      changeValue(val) {
        this.innerValue = val;
        this.$emit('input', val);
        /**
         * change ids + items
         * */
        var items = [];
        if (val && val.length) {
          for (let i = 0; i < val.length; i++) {
            var id = val[i];
            var index = this.options.findIndex(item => item.value == id);
            if (index >= 0) {
              items.push(this.options[index]);
            }
          }
        }
        this.$emit('change', items);
      },
      ajaxList() {
        var self = this;
        if (!this.$props.code) return Promise.resolve([]);
        return ajaxDicList(this.$props.code).then(list => {
          this.$data.options = list||[];
        });
      },
    },
  };
</script>
